package com.onluy.framework.batis.type;


import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

public class StringTypeHandler extends BaseTypeHandler<Object>
{
  private final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss";

  private final Locale DEFAULT_LOCALE = Locale.getDefault();

  public void setParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException
  {
    ps.setString(i, objectToString(parameter));
  }

  public Object getResult(ResultSet resultset, String columnName) throws SQLException
  {
    Object s = resultset.getObject(columnName);
    return objectToString(s);
  }

  public Object getResult(CallableStatement callablestatement, int columnIndex) throws SQLException
  {
    Object s = callablestatement.getObject(columnIndex);
    return objectToString(s);
  }

  public Object getNullableResult(ResultSet resultset, String columnName) throws SQLException
  {
    Object s = resultset.getObject(columnName);
    return objectToString(s);
  }

  public Object getNullableResult(ResultSet resultset, int columnIndex) throws SQLException
  {
    Object s = resultset.getObject(columnIndex);
    return objectToString(s);
  }

  public Object getNullableResult(CallableStatement callablestatement, int columnIndex) throws SQLException
  {
    Object s = callablestatement.getObject(columnIndex);
    return objectToString(s);
  }

  public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException
  {
    ps.setString(i, parameter.toString());
  }

  private String objectToString(Object obj)
  {
    if (obj == null)
      return "";
    if ((obj instanceof Date)) {
      return new SimpleDateFormat(this.DEFAULT_PATTERN, this.DEFAULT_LOCALE).format(obj);
    }
    return obj.toString();
  }
}